package class1.echo;

import lombok.Data;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/8/29
 * FOR :EchoServer
 */
@Data
public class EchoServer {

    private ServerSocket serverSocket;

    private Socket socket;

    private PrintWriter writer;

    private BufferedReader reader;

    public EchoServer(int port) {
        try {
            // ServerSocket 构造方法负责把在操作系统中把当前进程注册为服务器进程
            serverSocket = new ServerSocket(port);
            System.out.println("服务已经开启!");
        } catch (IOException e) {
            System.out.println("服务开启失败");
        }
    }

    /**
     * 写方法
     *
     * @param msg
     * @return
     */
    private String echo(String msg) {
        return "echo:" + msg;
    }

    /**
     * 获取写入流
     *
     * @param socket
     * @return
     */
    private PrintWriter getWriter(Socket socket) {
        try {
            OutputStream outputStream = socket.getOutputStream();
            return new PrintWriter(outputStream,true);
        } catch (IOException e) {
            System.out.println("获取PrintWriter错误");
            return null;
        }
    }

    /**
     * 获取缓冲读入流
     *
     * @param socket
     * @return
     */
    private BufferedReader getReader(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            return new BufferedReader(new InputStreamReader(inputStream));
        } catch (IOException e) {
            System.out.println("获取BufferReader错误");
            return null;
        }
    }

    /**
     * 服务方法
     */
    public void service() {
        try {
            while (true) {
                // accept方法会一直监听端口等待客户的请求连接，一旦监听到就会返回一个Soket对象，形成一条通信回路
                socket = serverSocket.accept();
                // soket 对象提供了输入流和输出流，程序只要往socket里面写程序就会得到对应的通信数据
                System.out.println("有人连接上来了哦! ip:" + socket.getInetAddress() + ":" + socket.getPort());
                reader = getReader(socket);
                writer = getWriter(socket);
                String msg = null;
                while ((msg = reader.readLine()) != null) {
                    System.out.println(msg);
                    writer.println(echo(msg));
                    if ("bye".equals(msg))
                        break;
                }
            }
        } catch (IOException e) {
            System.out.println("读写出现异常");
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new EchoServer(9000).service();
    }
}
